#include "Mutex.hpp"
#include "Thread.hpp"
#include <iostream>

#include "Thread.hpp"
#include <vector>

#define NUM 4
using namespace ThreadModule;
using namespace LockModule;

// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int ticknumber = 1000;
class ThreadData
{
public:
    Mutex *lock_ptr;
    std::string name;
};

void ticket(ThreadData& d){
    while(true){
        d.lock_ptr->Lock();
        if (ticknumber > 0){
            usleep(1000);
            printf("%s buy a tick, ticknumber is : %d\n",d.name.c_str(), ticknumber--);
             d.lock_ptr->Unlock();
        }
        else
        {
            //如果没有票的话，我们需要把锁释放掉。
            d.lock_ptr->Unlock();
            //如果我们没有票的时候我们不退出呢? 并且票数是没5秒增加呢??
        }
        usleep(50);
    }
}

// void ticket(ThreadData &d)
// {
//     while (true)
//     {
//         {
//             LockGuard lock(*d.lock_ptr);
//             if (ticknumber > 0)
//             {
//                 usleep(1000);
//                 printf("%s buy a tick, ticknumber is : %d\n", d.name.c_str(), ticknumber--);
//             }
//             else
//             {
//                 // 如果没有票的话，我们需要把锁释放掉。
//                 break;
//             }
//         }
//         usleep(50);
//     }
// }

int main()
{
    Mutex mutex;
    std::vector<Thread<ThreadData>> threads;
    for (int i = 0; i < NUM; i++)
    {
        ThreadData *d = new ThreadData();
        d->lock_ptr = &mutex;
        threads.emplace_back(ticket, *d);
        d->name = threads.back().Name();
    }

    for (int i = 0; i < NUM; i++)
    {
        threads[i].Start();
    }

    for (int i = 0; i < NUM; i++)
    {
        threads[i].Join();
    }
    return 0;
}